<template>
  <div class="import-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>Excel文件导入</span>
      </div>

      <!-- 文件上传 -->
      <div class="upload-section">
        <el-upload
          ref="upload"
          :action="uploadUrl"
          :headers="headers"
          :on-success="handleSuccess"
          :on-error="handleError"
          :before-upload="beforeUpload"
          :auto-upload="false"
          accept=".xlsx,.xls"
        >
          <el-button slot="trigger" type="primary">选择文件</el-button>
          <el-button type="success" @click="submitUpload">开始导入</el-button>
        </el-upload>
      </div>

      <!-- 数据预览 -->
      <div v-if="previewData.length" class="preview-section">
        <el-table :data="previewData" border style="width: 100%">
          <el-table-column prop="courseName" label="课程名称" align="center" />
          <el-table-column prop="credit" label="学分" align="center" />
          <el-table-column prop="semester" label="学期" align="center" />
          <el-table-column prop="courseAttribute" label="课程属性" align="center" />
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import { importExcel } from '@/api/curriculum'
import { getToken } from '@/utils/auth'

export default {
  name: 'CurriculumImport',
  data() {
    return {
      uploadUrl: '/curriculum/import', // 后端接口地址
      headers: {
        Authorization: `Bearer ${getToken()}`
      },
      previewData: []
    }
  },
  methods: {
    // 提交上传
    submitUpload() {
      this.$refs.upload.submit()
    },

    // 文件校验
    beforeUpload(file) {
      const isValid = /\.(xlsx|xls)$/.test(file.name)
      if (!isValid) {
        this.$message.error('只能上传 Excel 文件')
      }
      return isValid
    },

    // 成功回调
    handleSuccess(response, file) {
      this.$message.success('文件导入成功')
      this.previewData = response.data || []
    },

    // 错误回调
    handleError(error, file) {
      this.$message.error(`导入失败：${error.message}`)
    }
  }
}
</script>

<style scoped>
.import-container {
  padding: 20px;
}

.upload-section {
  margin-bottom: 20px;
}

.preview-section {
  margin-top: 20px;
}
</style>
